/**
 * 购物车管理 API
 * 
 * 基于新的数据库结构，支持产品快照机制
 * 购物车中存储了产品添加时的完整信息快照，确保数据一致性
 * 
 * API 列表：
 * GET    /api/cart              - 获取购物车列表
 * GET    /api/cart/summary      - 获取购物车统计信息
 * POST   /api/cart              - 添加商品到购物车
 * PUT    /api/cart/:id          - 更新购物车项目
 * DELETE /api/cart/:id          - 删除购物车项目
 * POST   /api/cart/batch-delete - 批量删除购物车项目
 * DELETE /api/cart/clear        - 清空购物车
 * PATCH  /api/cart/:id/select   - 选择/取消选择购物车项目
 * PATCH  /api/cart/select-all   - 全选/取消全选
 * GET    /api/cart/check-stock  - 检查库存状态
 * POST   /api/cart/refresh      - 刷新购物车产品信息
 * GET    /api/cart/recommendations - 获取推荐商品
 * POST   /api/cart/estimate-shipping - 预估运费
 */

import Router from 'koa-router';
import { pool } from '../../config/database';
import { authMiddleware } from '../../middleware/auth';
import { RowDataPacket, ResultSetHeader } from 'mysql2';
import { ApiResponse, JwtPayload } from '../../types';

const router = new Router({ prefix: '/api/cart' });

// 购物车项目接口 - 匹配新的数据库结构
interface CartItem {
  id: number;
  user_id: number;
  product_id: number;
  quantity: number;
  selected: boolean;
  
  // 产品快照信息
  product_snapshot: any;
  
  // 常用字段
  product_name: string;
  product_brand?: string;
  product_category?: string;
  product_price: number;
  product_original_price?: number;
  product_image?: string;
  product_sku?: string;
  product_model?: string;
  product_slug?: string;
  
  // 库存状态
  in_stock: boolean;
  stock_count?: number;
  
  // 评价信息
  rating?: number;
  review_count?: number;
  view_count?: number;
  sales?: number;
  
  // 产品规格等
  specs?: any;
  features?: any;
  tags?: any;
  images?: any;
  
  // 时间戳
  created_at: string;
  updated_at: string;
  product_updated_at?: string;
}

// 获取购物车列表
router.get('/', authMiddleware, async (ctx) => {
  try {
    const user = ctx.state.user as JwtPayload;

    const [cartItems] = await pool.query(
      `SELECT * FROM cart_items 
       WHERE user_id = ? 
       ORDER BY created_at DESC`,
      [user.id]
    ) as [RowDataPacket[], any];

    // 处理JSON字段和数据类型转换
    const items = cartItems.map(item => ({
      ...item,
      selected: Boolean(item.selected),
      in_stock: Boolean(item.in_stock),
      product_snapshot: item.product_snapshot ? 
        (typeof item.product_snapshot === 'string' ? JSON.parse(item.product_snapshot) : item.product_snapshot) : {},
      specs: item.specs ? 
        (typeof item.specs === 'string' ? JSON.parse(item.specs) : item.specs) : {},
      features: item.features ? 
        (typeof item.features === 'string' ? JSON.parse(item.features) : item.features) : [],
      tags: item.tags ? 
        (typeof item.tags === 'string' ? JSON.parse(item.tags) : item.tags) : [],
      images: item.images ? 
        (typeof item.images === 'string' ? JSON.parse(item.images) : item.images) : []
    }));

    ctx.body = {
      success: true,
      data: items
    } as ApiResponse<CartItem[]>;
  } catch (error: any) {
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: '获取购物车失败：' + error.message
    } as ApiResponse;
  }
});

// 获取购物车统计信息
router.get('/summary', authMiddleware, async (ctx) => {
  try {
    const user = ctx.state.user as JwtPayload;

    const [cartItems] = await pool.query(
      `SELECT quantity, selected, product_price, product_original_price, in_stock
       FROM cart_items 
       WHERE user_id = ?`,
      [user.id]
    ) as [RowDataPacket[], any];

    const totalItems = cartItems.reduce((sum, item) => sum + item.quantity, 0);
    const selectedItems = cartItems.filter(item => item.selected).reduce((sum, item) => sum + item.quantity, 0);
    const totalPrice = cartItems.filter(item => item.selected).reduce((sum, item) => sum + (item.product_price * item.quantity), 0);
    const originalTotalPrice = cartItems.filter(item => item.selected).reduce((sum, item) => sum + ((item.product_original_price || item.product_price) * item.quantity), 0);
    const savings = originalTotalPrice - totalPrice;
    const shippingFee = totalPrice > 199 ? 0 : 15; // 满199免运费
    const finalPrice = totalPrice + shippingFee;

    // 额外统计信息
    const selectedItemsCount = cartItems.filter(item => item.selected).length;
    const outOfStockCount = cartItems.filter(item => !item.in_stock).length;
    const availableCount = cartItems.filter(item => item.in_stock).length;

    ctx.body = {
      success: true,
      data: {
        totalItems,
        selectedItems,
        totalPrice: Math.round(totalPrice * 100) / 100, // 保留两位小数
        originalTotalPrice: Math.round(originalTotalPrice * 100) / 100,
        savings: Math.round(savings * 100) / 100,
        shippingFee,
        finalPrice: Math.round(finalPrice * 100) / 100,
        selectedItemsCount,
        outOfStockCount,
        availableCount
      }
    } as ApiResponse;
  } catch (error: any) {
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: '获取购物车统计失败：' + error.message
    } as ApiResponse;
  }
});

// 添加商品到购物车
router.post('/', authMiddleware, async (ctx) => {
  try {
    const user = ctx.state.user as JwtPayload;
    const { productId, quantity = 1 } = ctx.request.body as any;

    if (!productId) {
      ctx.status = 400;
      ctx.body = {
        success: false,
        message: '产品ID不能为空'
      } as ApiResponse;
      return;
    }

    // 获取产品完整信息
    const [products] = await pool.query(
      'SELECT * FROM products WHERE id = ?',
      [productId]
    ) as [RowDataPacket[], any];

    if (products.length === 0) {
      ctx.status = 404;
      ctx.body = {
        success: false,
        message: '商品不存在'
      } as ApiResponse;
      return;
    }

    const product = products[0];

    // 检查库存
    if (product.stock < quantity) {
      ctx.status = 400;
      ctx.body = {
        success: false,
        message: '库存不足'
      } as ApiResponse;
      return;
    }

    // 检查购物车中是否已有相同商品
    const [existingItems] = await pool.query(
      'SELECT * FROM cart_items WHERE user_id = ? AND product_id = ?',
      [user.id, productId]
    ) as [RowDataPacket[], any];

    if (existingItems.length > 0) {
      // 更新数量
      const newQuantity = existingItems[0].quantity + quantity;
      if (newQuantity > product.stock) {
        ctx.status = 400;
        ctx.body = {
          success: false,
          message: '购物车中商品总数量超过库存'
        } as ApiResponse;
        return;
      }

      await pool.query(
        'UPDATE cart_items SET quantity = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?',
        [newQuantity, existingItems[0].id]
      );

      ctx.body = {
        success: true,
        message: '商品已添加到购物车'
      } as ApiResponse;
    } else {
      // 构建产品快照
      const productSnapshot = {
        id: product.id,
        name: product.name,
        brand: product.brand,
        category: product.category,
        price: product.price,
        originalPrice: product.original_price,
        rating: product.rating,
        reviewCount: product.review_count || 0,
        viewCount: product.view_count || 0,
        image: product.images ? (Array.isArray(product.images) ? product.images[0] : JSON.parse(product.images)[0]) : '',
        images: product.images ? (Array.isArray(product.images) ? product.images : JSON.parse(product.images)) : [],
        inStock: product.stock > 0,
        stockCount: product.stock,
        description: product.description || product.short_description,
        specs: product.specifications ? (typeof product.specifications === 'string' ? JSON.parse(product.specifications) : product.specifications) : {},
        features: product.features ? (typeof product.features === 'string' ? JSON.parse(product.features) : product.features) : [],
        tags: product.tags ? (typeof product.tags === 'string' ? JSON.parse(product.tags) : product.tags) : [],
        sales: product.sales || 0,
        slug: product.slug,
        sku: product.sku,
        model: product.model
      };

      // 添加新商品到购物车
      await pool.query(
        `INSERT INTO cart_items (
          user_id, product_id, quantity, selected,
          product_snapshot, product_name, product_brand, product_category,
          product_price, product_original_price, product_image, product_sku,
          product_model, product_slug, in_stock, stock_count, rating,
          review_count, view_count, sales, specs, features, tags, images
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
        [
          user.id,
          productId,
          quantity,
          1, // selected
          JSON.stringify(productSnapshot),
          product.name,
          product.brand,
          product.category,
          product.price,
          product.original_price,
          productSnapshot.image,
          product.sku,
          product.model,
          product.slug,
          product.stock > 0 ? 1 : 0,
          product.stock,
          product.rating,
          product.review_count || 0,
          product.view_count || 0,
          product.sales || 0,
          JSON.stringify(productSnapshot.specs),
          JSON.stringify(productSnapshot.features),
          JSON.stringify(productSnapshot.tags),
          JSON.stringify(productSnapshot.images)
        ]
      );

      ctx.body = {
        success: true,
        message: '商品已添加到购物车'
      } as ApiResponse;
    }
  } catch (error: any) {
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: '添加到购物车失败：' + error.message
    } as ApiResponse;
  }
});

// 更新购物车项目
router.put('/:id', authMiddleware, async (ctx) => {
  try {
    const user = ctx.state.user as JwtPayload;
    const cartItemId = parseInt(ctx.params.id);
    const { quantity, selected } = ctx.request.body as any;

    // 验证 ID 参数
    if (isNaN(cartItemId) || cartItemId <= 0) {
      ctx.status = 400;
      ctx.body = {
        success: false,
        message: '无效的购物车项目ID'
      } as ApiResponse;
      return;
    }

    // 检查购物车项目是否属于当前用户
    const [cartItems] = await pool.query(
      'SELECT * FROM cart_items WHERE id = ? AND user_id = ?',
      [cartItemId, user.id]
    ) as [RowDataPacket[], any];

    if (cartItems.length === 0) {
      ctx.status = 404;
      ctx.body = {
        success: false,
        message: '购物车项目不存在'
      } as ApiResponse;
      return;
    }

    // 如果更新数量，检查当前库存快照和实际库存
    if (quantity !== undefined) {
      // 先检查购物车中的库存快照
      const cartItem = cartItems[0];
      if (quantity > cartItem.stock_count) {
        ctx.status = 400;
        ctx.body = {
          success: false,
          message: '库存不足'
        } as ApiResponse;
        return;
      }

      // 可选：检查实际产品库存（为了确保数据一致性）
      const [products] = await pool.query(
        'SELECT stock FROM products WHERE id = ?',
        [cartItem.product_id]
      ) as [RowDataPacket[], any];

      if (products.length > 0 && quantity > products[0].stock) {
        // 如果实际库存不足，更新购物车中的库存信息
        await pool.query(
          'UPDATE cart_items SET stock_count = ?, in_stock = ? WHERE id = ?',
          [products[0].stock, products[0].stock > 0 ? 1 : 0, cartItemId]
        );

        ctx.status = 400;
        ctx.body = {
          success: false,
          message: '库存不足，库存信息已更新'
        } as ApiResponse;
        return;
      }
    }

    // 构建更新字段
    const updateFields = [];
    const updateValues = [];

    if (quantity !== undefined) {
      updateFields.push('quantity = ?');
      updateValues.push(quantity);
    }

    if (selected !== undefined) {
      updateFields.push('selected = ?');
      updateValues.push(selected);
    }

    if (updateFields.length === 0) {
      ctx.status = 400;
      ctx.body = {
        success: false,
        message: '没有要更新的字段'
      } as ApiResponse;
      return;
    }

    updateFields.push('updated_at = CURRENT_TIMESTAMP');
    updateValues.push(cartItemId, user.id);

    await pool.query(
      `UPDATE cart_items SET ${updateFields.join(', ')} WHERE id = ? AND user_id = ?`,
      updateValues
    );

    ctx.body = {
      success: true,
      message: '购物车项目更新成功'
    } as ApiResponse;
  } catch (error: any) {
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: '更新购物车项目失败：' + error.message
    } as ApiResponse;
  }
});

// 删除购物车项目
router.delete('/:id', authMiddleware, async (ctx) => {
  try {
    const user = ctx.state.user as JwtPayload;
    const cartItemId = parseInt(ctx.params.id);

    // 验证 ID 参数
    if (isNaN(cartItemId) || cartItemId <= 0) {
      ctx.status = 400;
      ctx.body = {
        success: false,
        message: '无效的购物车项目ID'
      } as ApiResponse;
      return;
    }

    const result = await pool.query(
      'DELETE FROM cart_items WHERE id = ? AND user_id = ?',
      [cartItemId, user.id]
    ) as [ResultSetHeader, any];

    if (result[0].affectedRows === 0) {
      ctx.status = 404;
      ctx.body = {
        success: false,
        message: '购物车项目不存在'
      } as ApiResponse;
      return;
    }

    ctx.body = {
      success: true,
      message: '商品已从购物车删除'
    } as ApiResponse;
  } catch (error: any) {
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: '删除购物车项目失败：' + error.message
    } as ApiResponse;
  }
});

// 批量删除购物车项目
router.post('/batch-delete', authMiddleware, async (ctx) => {
  try {
    const user = ctx.state.user as JwtPayload;
    const { ids } = ctx.request.body as { ids: number[] };

    if (!ids || !Array.isArray(ids) || ids.length === 0) {
      ctx.status = 400;
      ctx.body = {
        success: false,
        message: '请提供要删除的商品ID列表'
      } as ApiResponse;
      return;
    }

    // 验证所有 ID 参数
    const validIds = ids.filter(id => !isNaN(id) && id > 0);
    if (validIds.length === 0) {
      ctx.status = 400;
      ctx.body = {
        success: false,
        message: '所有提供的ID都无效'
      } as ApiResponse;
      return;
    }

    if (validIds.length !== ids.length) {
      // 如果有部分无效ID，记录警告但继续处理有效ID
      console.warn('批量删除购物车项目时发现无效ID:', ids.filter(id => isNaN(id) || id <= 0));
    }

    const placeholders = validIds.map(() => '?').join(',');
    const result = await pool.query(
      `DELETE FROM cart_items WHERE id IN (${placeholders}) AND user_id = ?`,
      [...validIds, user.id]
    ) as [ResultSetHeader, any];

    ctx.body = {
      success: true,
      message: `批量删除成功，共删除 ${result[0].affectedRows} 个商品`,
      deletedCount: result[0].affectedRows
    } as ApiResponse;
  } catch (error: any) {
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: '批量删除失败：' + error.message
    } as ApiResponse;
  }
});

// 清空购物车
router.delete('/clear', authMiddleware, async (ctx) => {
  try {
    const user = ctx.state.user as JwtPayload;

    await pool.query(
      'DELETE FROM cart_items WHERE user_id = ?',
      [user.id]
    );

    ctx.body = {
      success: true,
      message: '购物车已清空'
    } as ApiResponse;
  } catch (error: any) {
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: '清空购物车失败：' + error.message
    } as ApiResponse;
  }
});

// 选择/取消选择购物车项目
router.patch('/:id/select', authMiddleware, async (ctx) => {
  try {
    const user = ctx.state.user as JwtPayload;
    const cartItemId = parseInt(ctx.params.id);
    const { selected } = ctx.request.body as { selected: boolean };

    // 验证 ID 参数
    if (isNaN(cartItemId) || cartItemId <= 0) {
      ctx.status = 400;
      ctx.body = {
        success: false,
        message: '无效的购物车项目ID'
      } as ApiResponse;
      return;
    }

    const result = await pool.query(
      'UPDATE cart_items SET selected = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ? AND user_id = ?',
      [selected, cartItemId, user.id]
    ) as [ResultSetHeader, any];

    if (result[0].affectedRows === 0) {
      ctx.status = 404;
      ctx.body = {
        success: false,
        message: '购物车项目不存在'
      } as ApiResponse;
      return;
    }

    ctx.body = {
      success: true,
      message: '选择状态更新成功'
    } as ApiResponse;
  } catch (error: any) {
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: '更新选择状态失败：' + error.message
    } as ApiResponse;
  }
});

// 全选/取消全选
router.patch('/select-all', authMiddleware, async (ctx) => {
  try {
    const user = ctx.state.user as JwtPayload;
    const { selected } = ctx.request.body as { selected: boolean };

    await pool.query(
      'UPDATE cart_items SET selected = ?, updated_at = CURRENT_TIMESTAMP WHERE user_id = ?',
      [selected, user.id]
    );

    ctx.body = {
      success: true,
      message: '全选状态更新成功'
    } as ApiResponse;
  } catch (error: any) {
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: '更新全选状态失败：' + error.message
    } as ApiResponse;
  }
});

// 检查库存状态
router.get('/check-stock', authMiddleware, async (ctx) => {
  try {
    const user = ctx.state.user as JwtPayload;

    // 获取购物车信息
    const [cartItems] = await pool.query(
      `SELECT * FROM cart_items WHERE user_id = ?`,
      [user.id]
    ) as [RowDataPacket[], any];

    // 获取当前实际库存信息
    const productIds = cartItems.map(item => item.product_id);
    if (productIds.length === 0) {
      ctx.body = {
        success: true,
        data: {
          available: [],
          outOfStock: [],
          insufficient: [],
          updated: []
        }
      } as ApiResponse;
      return;
    }

    const placeholders = productIds.map(() => '?').join(',');
    const [products] = await pool.query(
      `SELECT id, stock FROM products WHERE id IN (${placeholders})`,
      productIds
    ) as [RowDataPacket[], any];

    const productStockMap = new Map();
    products.forEach(product => {
      productStockMap.set(product.id, product.stock);
    });

    // 分析库存状态
    const available = [];
    const outOfStock = [];
    const insufficient = [];
    const updated = [];

    for (const item of cartItems) {
      const currentStock = productStockMap.get(item.product_id) || 0;
      const cartStock = item.stock_count || 0;

      // 如果库存信息不一致，更新购物车中的库存信息
      if (currentStock !== cartStock) {
        await pool.query(
          'UPDATE cart_items SET stock_count = ?, in_stock = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?',
          [currentStock, currentStock > 0 ? 1 : 0, item.id]
        );
        updated.push({
          ...item,
          old_stock: cartStock,
          new_stock: currentStock
        });
      }

      // 分类库存状态
      if (currentStock === 0) {
        outOfStock.push({
          ...item,
          current_stock: currentStock
        });
      } else if (currentStock < item.quantity) {
        insufficient.push({
          ...item,
          current_stock: currentStock,
          needed: item.quantity,
          shortage: item.quantity - currentStock
        });
      } else {
        available.push({
          ...item,
          current_stock: currentStock
        });
      }
    }

    ctx.body = {
      success: true,
      data: {
        available,
        outOfStock,
        insufficient,
        updated,
        summary: {
          total: cartItems.length,
          availableCount: available.length,
          outOfStockCount: outOfStock.length,
          insufficientCount: insufficient.length,
          updatedCount: updated.length
        }
      }
    } as ApiResponse;
  } catch (error: any) {
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: '检查库存失败：' + error.message
    } as ApiResponse;
  }
});

// 获取推荐商品
router.get('/recommendations', authMiddleware, async (ctx) => {
  try {
    const { limit = 8 } = ctx.query;

    // 简单的推荐逻辑：返回热门商品
    const [products] = await pool.query(
      `SELECT * FROM products 
       WHERE status = 'active' AND stock > 0 
       ORDER BY sales DESC, rating DESC 
       LIMIT ?`,
      [Number(limit)]
    ) as [RowDataPacket[], any];

    ctx.body = {
      success: true,
      data: products
    } as ApiResponse;
  } catch (error: any) {
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: '获取推荐商品失败：' + error.message
    } as ApiResponse;
  }
});

// 刷新购物车产品信息
router.post('/refresh', authMiddleware, async (ctx) => {
  try {
    const user = ctx.state.user as JwtPayload;
    const { productIds } = ctx.request.body as { productIds?: number[] };

    let whereClause = 'WHERE user_id = ?';
    let queryParams = [user.id];

    if (productIds && productIds.length > 0) {
      const placeholders = productIds.map(() => '?').join(',');
      whereClause += ` AND product_id IN (${placeholders})`;
      queryParams.push(...productIds);
    }

    // 获取要更新的购物车项目
    const [cartItems] = await pool.query(
      `SELECT * FROM cart_items ${whereClause}`,
      queryParams
    ) as [RowDataPacket[], any];

    if (cartItems.length === 0) {
      ctx.body = {
        success: true,
        message: '没有需要刷新的商品',
        data: { updated: 0 }
      } as ApiResponse;
      return;
    }

    // 获取最新的产品信息
    const productIdsList = cartItems.map(item => item.product_id);
    const placeholders = productIdsList.map(() => '?').join(',');
    const [products] = await pool.query(
      `SELECT * FROM products WHERE id IN (${placeholders})`,
      productIdsList
    ) as [RowDataPacket[], any];

    const productMap = new Map();
    products.forEach(product => {
      productMap.set(product.id, product);
    });

    let updatedCount = 0;

    // 更新每个购物车项目
    for (const cartItem of cartItems) {
      const product = productMap.get(cartItem.product_id);
      if (!product) continue;

      // 构建新的产品快照
      const productSnapshot = {
        id: product.id,
        name: product.name,
        brand: product.brand,
        category: product.category,
        price: product.price,
        originalPrice: product.original_price,
        rating: product.rating,
        reviewCount: product.review_count || 0,
        viewCount: product.view_count || 0,
        image: product.images ? (Array.isArray(product.images) ? product.images[0] : JSON.parse(product.images)[0]) : '',
        images: product.images ? (Array.isArray(product.images) ? product.images : JSON.parse(product.images)) : [],
        inStock: product.stock > 0,
        stockCount: product.stock,
        description: product.description || product.short_description,
        specs: product.specifications ? (typeof product.specifications === 'string' ? JSON.parse(product.specifications) : product.specifications) : {},
        features: product.features ? (typeof product.features === 'string' ? JSON.parse(product.features) : product.features) : [],
        tags: product.tags ? (typeof product.tags === 'string' ? JSON.parse(product.tags) : product.tags) : [],
        sales: product.sales || 0,
        slug: product.slug,
        sku: product.sku,
        model: product.model
      };

      // 更新购物车项目
      await pool.query(
        `UPDATE cart_items SET
          product_snapshot = ?,
          product_name = ?,
          product_brand = ?,
          product_category = ?,
          product_price = ?,
          product_original_price = ?,
          product_image = ?,
          product_sku = ?,
          product_model = ?,
          product_slug = ?,
          in_stock = ?,
          stock_count = ?,
          rating = ?,
          review_count = ?,
          view_count = ?,
          sales = ?,
          specs = ?,
          features = ?,
          tags = ?,
          images = ?,
          product_updated_at = CURRENT_TIMESTAMP,
          updated_at = CURRENT_TIMESTAMP
        WHERE id = ?`,
        [
          JSON.stringify(productSnapshot),
          product.name,
          product.brand,
          product.category,
          product.price,
          product.original_price,
          productSnapshot.image,
          product.sku,
          product.model,
          product.slug,
          product.stock > 0 ? 1 : 0,
          product.stock,
          product.rating,
          product.review_count || 0,
          product.view_count || 0,
          product.sales || 0,
          JSON.stringify(productSnapshot.specs),
          JSON.stringify(productSnapshot.features),
          JSON.stringify(productSnapshot.tags),
          JSON.stringify(productSnapshot.images),
          cartItem.id
        ]
      );

      updatedCount++;
    }

    ctx.body = {
      success: true,
      message: `成功刷新 ${updatedCount} 个商品的信息`,
      data: { updated: updatedCount }
    } as ApiResponse;
  } catch (error: any) {
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: '刷新购物车失败：' + error.message
    } as ApiResponse;
  }
});

// 预估运费
router.post('/estimate-shipping', authMiddleware, async (ctx) => {
  try {
    // 简单的运费估算逻辑
    const shippingOptions = {
      standard: { fee: 15, days: '3-5天' },
      express: { fee: 25, days: '1-2天' },
      overnight: { fee: 35, days: '次日达' }
    };

    ctx.body = {
      success: true,
      data: shippingOptions
    } as ApiResponse;
  } catch (error: any) {
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: '估算运费失败：' + error.message
    } as ApiResponse;
  }
});

export default router; 